<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog system-user-dialog"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      :title="dataList.BorrowConfilm"
      align="center"
      :visible.sync="dialogFormVisible"
      @closed="cancel"
    >
      <div>
        <el-form
          :model="formData"
          :rules="formDataRules"
          status-icon
          label-width="140px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item
                :label="dataList.DeviceBorrowType"
                :label-width="formLabelWidth"
                prop="type"
              >
                <span>{{ formData.typeName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="dataList.DeviceBorrower"
                :label-width="formLabelWidth"
                prop="borrowPersonName"
              >
                <span>{{ formData.borrowPersonName }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                :label="dataList.DeviceBorrowTime"
                :label-width="formLabelWidth"
                prop="borrowTime"
                :error="errorMsg.borrowTime"
              >
                <span>{{ formatTime(formData.borrowTime) }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="dataList.DeviceBorrowReturnTime"
                :label-width="formLabelWidth"
                prop="returnDate"
                :error="errorMsg.returnDate"
              >
                <span>{{ formatTime(formData.returnDate) }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                :label="dataList.ReasonsOfBorrow"
                :label-width="formLabelWidth"
                prop="reason"
                :error="errorMsg.reason"
              >
                <span>{{ formData.reason }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="dataList.Deviceremark"
                :label-width="formLabelWidth"
                :error="errorMsg.remark"
              >
                <el-input
                  v-model="formData.remark"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div>
        <el-divider class="el-divider-specail" content-position="left"
          ><span>{{ dataList.BorrowOfDevice }}</span>
        </el-divider>
        <el-table
          :data="formData.deviceBorrowInfoDtoList"
          element-loading-text="Loading"
          fit
          highlight-current-row
        >
          >
          <el-table-column :label="dataList.DeviceNumber">
            <template slot-scope="scope">
              {{ scope.row.num }}
            </template>
          </el-table-column>
          <el-table-column
            :label="
              $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
            "
          >
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.DeviceSpecifications">
            <template slot-scope="scope">
              {{ scope.row.specifications }}
            </template>
          </el-table-column>

          <el-table-column :label="dataList.DeviceClassifyId">
            <template slot-scope="scope">
              {{ scope.row.classifyName }}
            </template>
          </el-table-column>

          <el-table-column :label="dataList.DeviceSupplierName">
            <template slot-scope="scope">
              {{ scope.row.supplierName }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.DeviceFactoryNum">
            <template slot-scope="scope">
              {{ scope.row.factoryNum }}
            </template>
          </el-table-column>

          <el-table-column :label="dataList.DeviceStatus">
            <template slot-scope="scope">
              {{ scope.row.statusName }}
            </template>
          </el-table-column>
          <el-table-column
            :label="
              $i18n.locale === 'en'
                ? dataList.eDeviceStorageAddress
                : dataList.DeviceStorageAddress
            "
          >
            <template slot-scope="scope">
              {{ scope.row.storageAddress }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.DevicePersonResponsibleId">
            <template slot-scope="scope">
              {{ scope.row.personResponsibleName }}
            </template>
          </el-table-column>

          <el-table-column :label="dataList.IsBorrow">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.borrowStatus"
                :placeholder="dataList.Placeholder"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div>
        <el-divider class="el-divider-specail" content-position="left"
          ><span>{{ dataList.EquipmentAndSparepartsList }}</span>
        </el-divider>
        <el-table
          :data="formData.deviceParts"
          border
          style="width: 100%"
          height="400px"
        >
          <el-table-column align="center" :label="dataList.Number" width="100">
            <template slot-scope="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="deviceNum"
            :label="dataList.DeviceNumber"
          />
          <el-table-column
            align="center"
            prop="deviceName"
            :label="
              $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
            "
          />
          <el-table-column align="center" prop="name" :label="dataList.Name" />
          <el-table-column
            align="center"
            prop="unit"
            :label="dataList.UnitOfMeasurement"
          />
          <el-table-column
            align="center"
            prop="count"
            :label="dataList.Quantity"
          />
          <el-table-column align="center">
            <template #header>
              <span style="color: red">*</span>
              <span>{{ dataList.BorrowQuantity }}</span>
            </template>
            <!-- @blur="handleInputBlur(scope.row)" -->
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.loanCount"
                autocomplete="off"
                :validate-event="false"
              ></el-input
            ></template>
          </el-table-column>
          <el-table-column align="center" :label="dataList.Deviceremark">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" autocomplete="off"></el-input
            ></template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit('formData')">{{
          dataList.BorrowOfConfirm
        }}</el-button>
        <el-button @click="cancel">{{ btn.Cancel }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { get, borrowUpdate } from "../../api/DeviceBorrow.js";
import { GetListNoPage } from "../../api/DeviceParts";
import { YesAndNo } from "../../utils/const";
import { formatTime } from "../../utils/time";
export default {
  name: "DeviceBorrowConfirmDialog",
  components: {},
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      options: YesAndNo,
      loading: false,
      formLabelWidth: "100px",
      list: [],
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      initData: {
        id: 0,
        num: "",
        type: 0,
        typeName: "",
        statusId: 0,
        statusName: "",
        reason: "",
        returnDate: null,
        borrowPersonId: "",
        borrowPersonName: "",
        creatorId: 0,
        creatorName: "",
        remark: "",
      },
      formData: {
        borrowTime: null,
        id: 0,
        num: "",
        type: 0,
        typeName: "",
        statusId: 0,
        statusName: "",
        reason: "",
        returnDate: null,
        borrowPersonId: this.$store.getters.currentUserId,
        borrowPersonName: "",
        creatorId: 0,
        creatorName: "",
        remark: "",
      },
      returnDateOptions: {
        // 限制日期
        disabledDate: (time) => {
          return time.getTime() < new Date(this.formData.borrowTime).getTime();
        },
      },
      pickerOptions: {
        // 限制日期
        disabledDate(time) {
          return time.getTime() < Date.now() - 3600 * 1000 * 24;
        },
      },
      formDataRules: {
        borrowTime: [
          {
            required: true,
            message: this.$t("ModuleDevice.Message.EntryIntoForceTime"),
            trigger: "change",
          },
          // { validator: validateDate, trigger: "change" },
        ],
        num: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        type: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        typeName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        statusId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        statusName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        reason: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        borrowPersonId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        borrowPersonName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        creatorId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        creatorName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        returnDate: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      initErrorMsg: {
        num: "",
        type: "",
        typeName: "",
        statusId: "",
        statusName: "",
        reason: "",
        returnDate: "",
        borrowPersonId: "",
        borrowPersonName: "",
        creatorId: "",
        creatorName: "",
        remark: "",
      },
      errorMsg: {
        num: "",
        type: "",
        typeName: "",
        statusId: "",
        statusName: "",
        reason: "",
        returnDate: "",
        borrowPersonId: "",
        borrowPersonName: "",
        creatorId: "",
        creatorName: "",
        remark: "",
      },
    };
  },
  computed: {
    btn() {
      return this.$t("ModuleDevice.buttons");
    },
    dataList() {
      return this.$t("ModuleDevice.Device");
    },
  },
  watch: {},
  created() {
    this.get();
  },
  methods: {
    formatTime,
    handleInputBlur(row) {
      // 正则表达式：必须为正整数
      const reg = /^[1-9]\d*$/;
      if (!reg.test(row.loanCount)) {
        this.$message.error(this.$t("ModuleDevice.Message.RegPositiveinteger"));
        row.loanCount = 1; // 重置为默认值
      }
    },
    cancel() {
      this.$emit("update:dialogFormVisible", false);
    },
    get() {
      get({ id: this.id })
        .then((res) => {
          this.formData = res.data;
          var deviceIdList = [];
          for (let i = 0; i < res.data.deviceBorrowInfoDtoList.length; i++) {
            deviceIdList.push(res.data.deviceBorrowInfoDtoList[i].deviceId);
          }
          var data = { deviceIdList: deviceIdList };
          GetListNoPage(data).then((res) => {
            for (let i = 0; i < res.data.length; i++) {
              res.data[i].loanCount = res.data[i].count;
            }
            this.formData.deviceParts = res.data;

            const idMap = new Map();
            this.formData.deviceBorrowInfoDtoList.forEach((item, index) => {
              idMap.set(item.id, index);
            });
            this.formData.deviceParts.sort((a, b) => {
              return idMap.get(a.deviceId) - idMap.get(b.deviceId);
            });
          });
        })
        .catch((res) => {});
    },
    closeDialog() {
      this.$parent.getList();
      this.cancel();
    },

    onSubmit() {
      debugger;
      var flag = true;
      this.formData.deviceBorrowInfoDtoList.map((item) => {
        if (item.borrowStatus === 0) {
          item.borrowStatusName = this.$t("ModuleDevice.Device.Deny");
        } else {
          item.borrowStatusName = this.$t("ModuleDevice.Device.Correct");
          flag = false;
        }
        item.id = item.deviceBorrowInfoId; // 确认提交
      });
      var state = true;
      this.formData.deviceParts.forEach((row) => {
        const reg = /^[0-9]\d*$/;
        if (!reg.test(row.loanCount)) {
          this.$message.error(
            this.$t("ModuleDevice.Message.RegPositiveinteger")
          );
          // row.loanCount = 1; // 重置为默认值
          state = false;
          return false;
        }
      });
      if (!state) {
        return false;
      }

      if (flag) {
        this.$message.warning(
          this.$t(
            "ModuleDevice.Message.AtLeastoneborrowingdeviceselectionisrequired"
          )
        ); // "最少一个借用设备选择是");
        return;
      }
      this.formData.deviceBorrowInfoList =
        this.formData.deviceBorrowInfoDtoList;
      borrowUpdate(this.formData)
        .then((res) => {
          this.closeDialog();
        })
        .catch((res) => {});
    },
  },
};
</script>
